<?php
session_start();
if (!isset($_SESSION['user_privileg_role']))
    $_SESSION['user_privileg_role'] = 0;
if (isset($_SESSION['cur_user'])) {
    header("Location: ./");
    exit;
}

if (isset($_POST['login']) && isset($_POST["pass"])) {
    $prelogin = preg_replace("/[^\w_\.\-]/", "", $_POST['login']);
    $prepass = trim($_POST["pass"]);

    $dbLocation = "127.0.0.1";
    $dbname = "web-articles";
    $dbuser = "root";
    $dbpasswd = "root";

    $dbcnx = @mysql_connect($dbLocation, $dbuser, $dbpasswd);

    if (!$dbcnx) {
        echo 'mySQL server error';
        exit();
    }
    if (!@mysql_select_db($dbname, $dbcnx)) {
        echo 'database is unavailable';
        exit();
    }
    $user_result = mysql_query("SELECT * FROM users WHERE name='$prelogin' AND pass='" . $prepass . "'");
    if (mysql_error())
        die(mysql_error());

    elseif (@mysql_num_rows($user_result) != 1)
        $login_error = "Неверное имя пользователя или пароль.";
    else {
        $row = mysql_fetch_array($user_result);
        $_SESSION['cur_user'] = $row['name'];
        $_SESSION['cur_user_admin'] = $row['is_admin'];
        if ($_SESSION['cur_user_admin'] == true)
            $_SESSION['user_privileg_role'] = 10;
        else
            $_SESSION['user_privileg_role'] = 5;
        header("Location: ./");
        exit();
    }
}
?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
    <link rel="StyleSheet" type="text/css" href="style.css">

    <style type="text/css">html body {
        height: auto;
    }</style>
</head>
<body>

<a href="./" class="login-pas_to_index">На главную</a>

<form method="post" style="height:50%;" id="MyForm">
    <div style="margin:200px auto; width:250px;">
        <table style="width:250px;">
            <tr>
                <td colspan="2"><p class="header-text">Аутентификация</p></td>
            </tr>
            <tr>
                <td>Логин</td>
                <td><input name="login" type="text" maxlength="20" class="login-pas_inputs"></td>
            </tr>
            <tr>
                <td>Пароль</td>
                <td><input name="pass" type="password" maxlength="20" class="login-pas_inputs"></td>
            </tr>
            <tr>
                <td colspan="2"><input type=submit name=send value=Отправить style="margin-left:74px;"></td>
            </tr>
        </table>
        <?php if (isset($login_error)) echo "<span class='error'>$login_error</span>";?>
    </div>
</form>

</body>
</html>